#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
	PROJECT pyevocomm -
	
	APP		Core

	MODULE	controller protocol & utilities

	SITE DESCRIPTION http://code.google.com/p/pyevocomm/ 

	@copyright: 2012 by archetipo <alessio.gerace@gmail.com>
	@license: New BSD License, see COPYING for details.
"""

import os,sys
import pyglet
from pyglet.gl import *
from pyglet.gl import GL_TRIANGLES, GL_LINE_SMOOTH
from pyglet.gl.glext_arb import GL_QUAD_ALPHA4_SGIS
import cv
import freenect
from PIL import Image,ImageDraw, ImageFont
import ImageColor
from pymouse import PyMouse

class comandi_dati():
	def __init__(self):
		self.datleft={'rect':[],'area:':0,'col':cv.CV_RGB(255,0,0),'tipo':'left','centro':[0,0],'piano':0}
		self.datrigth={'rect':[],'area':0,'col':cv.CV_RGB(0,255,0),'tipo':'rigth','centro':[0,0],'piano':0}
		self.datsingle={'rect':[],'area':0,'col':cv.CV_RGB(100,200,150),'tipo':'single','centro':[0,0],'piano':0}
		self.datselect={'rect':[],'area':0,'col':cv.CV_RGB(63,240,63),'tipo':'select','centro':[0,0],'piano':0}
		self.datclose={'rect':[],'area':0,'col':cv.CV_RGB(150,200,150),'tipo':'close','centro':[0,0],'piano':0}
		self.datlang={'rect':[],'area':0,'col':cv.CV_RGB(200,200,150),'tipo':'lang','centro':[0,0],'piano':0}
		self.datstep={'rect':[],'area':0,'col':cv.CV_RGB(240,30,30),'tipo':'step','centro':[0,0],'piano':0}
		self.datinsel={'rect':[],'area':0,'col':cv.CV_RGB(231,231,70),'tipo':'insel','centro':[0,0],'piano':0}
		self.datlost={'rect':[],'area':0,'col':cv.CV_RGB(0,0,0),'tipo':'lost','centro':[0,0],'piano':0}
		self.dathwconn={'rect':[],'area':0,'col':cv.CV_RGB(0,0,0),'tipo':'hwc','centro':[0,0],'piano':0}
		self.datnos={'rect':[],'area':0,'col':cv.CV_RGB(0,0,0),'tipo':'nos','centro':[0,0],'piano':0}
		self.datmenu={'rect':[],'area':0,'col':cv.CV_RGB(0,0,0),'tipo':'menu','centro':[0,0],'piano':0}
datacom=comandi_dati()
#print datacom.datstep
class Graph_util():
	def __init__(self):
		self.m=PyMouse()
		self.size = m.screen_size()
		self.centerS=(self.size[0]/2,self.size[1]/2)
		self.hvideo=0
		self.wvideo=0
		self._hrif=768
		self._wrif=1366
#min 8 max 50
	def font(self,dim,h=0):
		hrif=self._hrif
		if h==0:
			h=self.m.screen_size()[1]
		k=float(float(dim)/float(hrif))
		return hvideo*k
	
	def x(dim):
		wr=self._wrif
		k=float(float(dim)/float(wr))
		return self.wvideo*k
			
	def y(dim):
		hr=self._hrif
		k=float(float(dim)/float(hr))
		return self.hvideo*k
	def scala(val=1.0):
		hr=self._hrif
		k=float(val/float(hr))
		return hvideo*k
	
	def movemouse():
		
		pos = (0,0)
		self.m.move(pos[0], size[1])
		self.m.move(pos[0]+1, size[1])
		self.m.move(pos[0], size[1])

class List_utils():

	#queste 2 funzioni mi generano una lista
	#con numeri float su un range a piacere con step a piacere
	#es (-1,1,0.33) drange fa lo step e listRange mi da la lista
	def drange(start,stop,step):
			r=start
			while r<=stop:
				yield r
				r+=step
				
	def listRange(start,stop,step):
		ir=drange(start,stop,step)
		return [x for x in ir]

	#funzione per avere la lista a 3 elementi
	#[i-1,i,i+1] da una lista qualsiasi
	#se la lista ha un solo eelemento viene rest [0,0,0]
	def treList(lista,cid):
		a=lista[cid]
		b=lista[cid]
		c=lista[cid]
		ret=[]
		if len(lista)==1:
			ret=[a,b,c]
		else:
			a=lista[cid-1]
			if cid==(len(lista)-1):
				c=lista[0]
			else:
				c=lista[cid+1]
				
			ret=[a,b,c]
		return ret
	#cerca l'id in una lisat di dizionari così fatta:
	#{'id':numero,'obj':oggetto o lista oggetti}
	#es
	#{'id':self.currid,'obj':[self.sxImg,self.frontImg,self.dxImg]}	
	def cercaInlista(id,lista):
		for x in range(len(lista)):
			if lista[x]['id']==id:
				return x
		return -1	
		
def screenshot(name='screenshot'):
    """
    Take a screenshot

    Parameters:
    name : string : Default 'screenshot'.  Name of the saved image.  Will
        always save as .png
    """
    # Get the 'the back-left color buffer'
    pyglet.image.get_buffer_manager().get_color_buffer().save('%s.png'%name)

def getPixelValue(x, y):
    """
    Return the RGBA 0-255 color value of the pixel at the x,y position.
    """
    # BufferManager, ColorBufferImage
    color_buffer = pyglet.image.get_buffer_manager().get_color_buffer()
    # AbstractImage, ImageData, sequece of bytes
    pix = color_buffer.get_region(x,y,1,1).get_image_data().get_data("RGBA", 4)
    return pix[0], pix[1], pix[2], pix[3]

def drawPoint(x, y, color):
    """
    Based on the (r,g,b) color passed in, draw a point at the given x,y coord.
    """
    pyglet.graphics.draw(1, GL_POINTS,
                         ('v2i', (x, y)),
                         ('c3B', (color[0], color[1], color[2]) ) )

def getSmoothConfig():
    """
    Sets up a configuration that allows of smoothing\antialiasing.
    The return of this is passed to the config parameter of the created window.
    """
    try:
        # Try and create a window config with multisampling (antialiasing)
        config = Config(sample_buffers=1, samples=4,
                        depth_size=16, double_buffer=True)
    except pyglet.window.NoSuchConfigException:
        print "Smooth contex could not be aquiried."
        config = None
    return config

def printEvents(window):
    """
    Debug tool that will print the events to the console.

    window is an instance of a Window object receiving the events.
    """
    window.push_handlers(pyglet.window.event.WindowEventLogger())

def playMusic(music):
    """
    Simple wrapper to play a music (mp3) file.

    music : music file relative to application.
    """
    music = pyglet.resource.media(music)
    music.play()

       
